<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="乐器名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入乐器名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:instrument:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:instrument:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:instrument:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:instrument:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <el-col :span="1.5">
        <el-dropdown @command="handleCommand" trigger="click">
          <el-button type="primary" plain size="mini">
            排序方式<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown" class="sort-dropdown">
            <el-dropdown-item v-for="item in sortOptions" :key="item.value" :command="item.value"
              :class="{ 'active-sort': queryParams.sortFiledName === item.value }">
              {{ item.label }}
              <i v-if="queryParams.orderByColumn === item.value" class="el-icon-check el-icon--right"
                style="color: #409EFF;"></i>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="instrumentList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" sortable="custom" />
      <el-table-column label="乐器名称" align="center" prop="name" sortable="custom" />
      <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" />
      <el-table-column label="更新时间" align="center" prop="updateTime" sortable="custom" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:instrument:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:instrument:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="handlePagination" />

    <!-- 添加或修改乐器分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="乐器名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入乐器名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInstrument, getInstrument, delInstrument, addInstrument, updateInstrument } from "@/api/system/instrument"

export default {
  name: "Instrument",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 乐器分类表格数据
      instrumentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sortFiledName: null,
        sort: 1
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      sortOptions: [
        { label: '按序号', value: 'id' },
        { label: '按名称', value: 'name' },
        { label: '按创建时间', value: 'createTime' },
        { label: '按更新时间', value: 'updateTime' }
      ]
    }
  },
  created() {
    // 初始化排序状态
    this.sortKey = 'id'; // 默认按ID排序
    this.getList();
  },
  methods: {
    /** 分页事件处理 */
    handlePagination(val) {
      this.queryParams.pageNum = val.page;
      this.queryParams.pageSize = val.limit;
      // 调用getList时传递当前的排序参数
      this.getList(this.queryParams.sortFiledName, this.queryParams.sort);
    },
    /** 查询乐器分类列表 */
    getList(sortFiledName, sort) {
      this.loading = true
      listInstrument({ ...this.queryParams, sortFiledName: sortFiledName, sort: sort }).then(response => {
        console.log(response)
        this.instrumentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加乐器分类"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getInstrument(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改乐器分类"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInstrument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInstrument(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除乐器分类编号为"' + ids + '"的数据项？').then(function () {
        return delInstrument(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/instrument/export', {
        ...this.queryParams
      }, `instrument_${new Date().getTime()}.xlsx`)
    },
    /** 排序 */
    handleSortChange(column, prop, order) {
      // 将前端驼峰命名字段转换为数据库下划线命名字段
      const mapFieldName = (field) => {
        const fieldMap = {
          'createTime': 'create_time',  // 驼峰转下划线
          'updateTime': 'update_time',  // 其他需要转换的字段可以在这里添加
          // 默认不转换
        };
        return fieldMap[field] || field;
      };

      const sortField = mapFieldName(column.prop);
      const sortOrder = column.order === 'descending' ? 0 : 1; // 0=DESC, 1=ASC
      this.queryParams.sortFiledName = sortField;
      this.queryParams.sort = sortOrder;
      this.getList(sortField, sortOrder);
    },
    /** 排序下拉菜单选择 */
    handleCommand(command) {
      // 将前端驼峰命名字段转换为数据库下划线命名字段
      const mapFieldName = (field) => {
        const fieldMap = {
          'createTime': 'create_time',  // 驼峰转下划线
          'updateTime': 'update_time',  // 其他需要转换的字段可以在这里添加
          // 默认不转换
        };
        return fieldMap[field] || field;
      };

      // 设置当前排序字段
      this.queryParams.sortFiledName = mapFieldName(command);
      
      // 如果点击的是当前已选中的排序字段，则切换排序方向
      if (this.sortKey === command) {
        this.queryParams.sort = this.queryParams.sort === 1 ? 0 : 1; // 切换排序方向
      } else {
        // 如果点击的是新的排序字段，默认使用升序
        this.sortKey = command;
        this.queryParams.sort = 1; // 默认升序
      }
      
    
      // 获取列表数据
      this.getList(this.queryParams.sortFiledName, this.queryParams.sort);
    },
  }
}
</script>

<style scoped>
::v-deep .sort-dropdown {
  min-width: 120px;

  .el-dropdown-menu__item {
    padding: 8px 20px;
    font-size: 12px;

    &:hover {
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }

  .active-sort {
    background-color: #f5f7fa;
  }
}
</style>
